<?php
namespace Utuo;

use My\Model\OrderModel;
use Home\Logic\OrderLogic;
use Home\Logic\PayLogic;
use My\Model\DeliveryModel;

abstract class OrderController extends DistributionShopForeground {
	
	/**
	 * 设置订单业务类
	 */
	protected function setOrderLogic() {
		OrderLogic::setDriver(OrderModel::ORDER_TYPE_COMMON, array(
			'cid' => $this->cid,
			'uid' => $this->uid,
		));
	}
	
	/**
	 * 初始化
	 */
	public function _init() {
		layout ( 'disshop' );
		$this->setModelName ( "DistributionShop" );
		$this->setModelControllerName( "DisShop" );
		$this->setOrderLogic();
	}
	
	/**
	 * 我的订单列表
	 */
	public function listAction() {
	    $type = I ( "type" );
	    $condition = array (
	        "orders.uid" => $this->uid,
	    );
	    
	    if ($type == 1) { // 未付款
	        $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_PAY;
	    } else if ($type == 2) { // 待签收(已付款,货到付款)
	        $condition ['orders.order_status'] = array (
	            "in",
	            array (
	                OrderModel::ORDER_STATUS_SHIPPING,
	                OrderModel::ORDER_STATUS_SIGN
	            )
	        );
	    } else if ($type == 3) { // 交易成功
	        $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_COMPLETED;
	    }  else if ($type == 4) { // 退款订单
	        $condition['orders.refund_times'] = array('gt', 0);
	    } else { // 其它
	        $condition ['orders.order_status'] = array (
	            "not in",
	            array (
	                OrderModel::ORDER_STATUS_PAY,
	                OrderModel::ORDER_STATUS_SHIPPING,
	                OrderModel::ORDER_STATUS_SIGN,
	                OrderModel::ORDER_STATUS_COMPLETED,
	            ),
	        );
	    }
	    
	    $orderLists = OrderLogic::getList($condition);
	    OrderLogic::bindOrdersDetail($orderLists);
	    $this->assign("types", OrderModel::$TYPES);
	    $this->assign ( "orderLists", $orderLists );
	    $tpl = method_exists($this, "getOrderListTpl") ? $this->getOrderListTpl() : "{$this->modelControllerName}/" . ACTION_NAME;
	    $this->display ( $tpl );
	}
	
	/**
	 * 订单结算页
	 * 无订单接收参数:
	 *  agentId 购买时代理商家id
	 *  goods 购买产品(选其一 goods/crtId)
	 *  crtId 购物车项bussinessId ',' 号间隔
	 * 示例:
	 *  gid=1&goods[1][颜色|白,尺寸|3][quantity]=1&crtId=1225455,58756645,45587156
	 *  gid=1&goods[1][-][quantity]=1
	 * 有订单接收参数:
	 *  orderId 订单id
	 */
	public function confirmOrderAction() {
		$orderId = I('orderId', 0, "intval");
		if ( $orderId ) {
			$order = OrderLogic::getPayingOrder( $orderId );
		} else {
			$agentId = $this->getRequestAid();
			$goods = (array)I('goods');	
			$crtId = I('crtId') and $crtId = explode(',', $crtId);
			$order = OrderLogic::getSaveingOrder( array(
				'agentId' => $agentId,
				'goods' => $goods,
				'crtId' => $crtId,
			) ) or $this->error(OrderLogic::getError());
			session ( "order", $order );
		}
		$this->assign ( "order", $order );
		$this->assign ("deliveryMethod", DeliveryModel::$METHOD);
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->assignPayApiList($order["support_cod"]);
		$tpl = method_exists($this, "getConfirmOrderTpl") ? $this->getConfirmOrderTpl() : "{$this->modelControllerName}/" . ACTION_NAME;
		$this->display ( $tpl );
	}
	
	/**
	 * 确认支付订单
	 */
	public function confirmOrderPostAction() {
		$orderId = I('orderId', 0, "intval"); // 订单id
		$orderNo = I ( 'orderNo', 0 ); // 订单单号
		$payApitype = I("apitype", ""); // 支付方式
		$buyMethod = I("buyMethod", 0, "intval"); // 购买方式
		
		if ( !$orderId ) { // 添加订单
			$order = session ( "order" );
			/* 验证订单下单重复 */
		    $orderNo and $orderSaved = M("Order")->where(array( 'order_no'=>$orderNo, 'cid'=>$this->cid) )->find();
		    $orderSaved and $this->error ( "订单($orderNo)已超时,正在转向订单详细重新结算.",  U(CONTROLLER_NAME.'/showOrder', "id={$orderSaved['id']}&sid={$this->cid}"));
			/* 验证订单超时 */
			if ( !$order || ($order and (time () - $order ["create_time"]) > 3*60) ) { // 下单超时
			    $this->error ( "订单($orderNo){$order ['orderNo']}已超时." );
			}
			/* 验证是否支持货到付款 */
			if( $payApitype == "COD" ) {
			    if ( !$order['support_cod'] ) {
			        $this->error ( "当前订单不支持货到付款" );
			    }
			}
			/* 验证收货地址  */
			if( empty($order['province']) ) {
			    $this->error ( "当前订单不支持货到付款" );
			}
			$orderId = OrderLogic::addOrder($order, $payApitype);
		} else { // 修改订单
		   
		}

		/* 支付转入 */
		if ( empty($payApitype) ) {
		    $order = OrderLogic::getOrder ( $orderId );
		    $this->assign ( "order", $order );
		    $this->display ( "{$this->modelControllerName}/showOrder" );
		} else {
		    $backUrl = urlencode(U(CONTROLLER_NAME.'/showOrder', "id={$orderId}&sid={$this->cid}"));
		    redirect(__APP__."/".MODULE_NAME."/PayX/toPay?id={$orderId}&sid={$this->cid}&apitype={$payApitype}&backUrl={$backUrl}");
		}
	}
	
	/**
	 * 确认收货
	 */
	public function signInAction() { 
	    $orderId = I ( "id", 0, "int" );
	    $result = OrderLogic::confirmSign($orderId);
	    if ( $result ) {
	        $this->ajaxSuccess("确认收货成功");
	    }
	    $this->ajaxError(OrderLogic::getError());
	}
	
	/**
	 * 订单详细
	 */
	public function showOrderAction() {
	    $id = I ( "id", 0, "intval" );
	    $order = OrderLogic::getOrder ( $id );
	    /* 待支付订单跳转入重新进入确认页 */
	    if ( in_array('pay', $order['buyerOperates'] ) ) { // 支付
	        $controller = CONTROLLER_NAME;
	        redirect(U("{$controller}/confirmOrder", array('sid'=>$this->cid, 'orderId'=>$id)));
	    }
	    $this->assign ( "order", $order );
	    $tpl = method_exists($this, "getShowOrderTpl") ? $this->getShowOrderTpl() : "{$this->modelControllerName}/" . ACTION_NAME;
	    $this->display ( $tpl );
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrderAction() { 
		
	}
	
	/**
	 * 支付方式
	 * @param unknown $supportCod
	 * @return Ambigous <\Home\Logic\multitype:, multitype:>
	 */
	private function assignPayApiList( $supportCod ) {
	    /* 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口) */
	    $produtPayApiLists = PayLogic::getPayApiList($this->cid);
	    if ( $supportCod ) { // 订单是否支持货到付款
	        $produtPayApiLists = array_merge($produtPayApiLists, array('COD' => "货到付款"));
	    }
	    $this->assign("payApiOptions", $this->getOption( $produtPayApiLists ));
	}
	
}